'use strict'
const userValidation = require('validation/user')
const validator = require('util/requestValidator')
const ApiError = require('errorException/apiError')
const redis = require('util/redis')
const utils = require('util/utils')


module.exports = {
  /**
    * @description 校验请求头，判断传过来的token和fid是否相等
    */
  checkHeader: async function(ctx, next) {
    await validator.validate(
      ctx.headerInput,
      userValidation.checkHeader.schema,
      userValidation.checkHeader.options
    )
    const authorization = ctx.headerInput.authorization
    const userInfo = await utils.verifyToken(authorization)
    const checkRedisToken = await redis.get(`blog:user:token:${userInfo.username}`) //  获取redis中未过期的token
    if (!ctx.headerInput.authorization || !checkRedisToken) {
      throw new ApiError('access.forbidden')
    }
    await next()
  }
}
